package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Name CategoryController
 * @Author stella
 * @Date 2023-03-02 12:10 PM
 */
@Api(tags = "分类管理")
@RestController
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    //分类列表
    @ApiOperation(value = "查询所有分类")
    @GetMapping("/category/findAll")
    public ResultInfo findAll() {
        List<Category> list = null;
        // 先查询缓存
        String categoryKey = "category_list";

        if (redisTemplate.hasKey(categoryKey)){
            // yes,redis has data
            list = (List<Category>) redisTemplate.opsForValue().get(categoryKey);
            log.info("查询redis缓存");
        }else{
            // no redis have not data
            list = categoryService.findAll();
            log.info("查询Mysql 数据库");
            // Synchronous save
            redisTemplate.opsForValue().set(categoryKey,list);
        }
        return ResultInfo.success(list);
    }

    //新增分类
    @ApiOperation(value = "新增分类")
    @PostMapping("/category")
    public ResultInfo save(@RequestBody Category c) {
        categoryService.save(c);
        // clean cache
        redisTemplate.delete("category_list");
        return ResultInfo.success();
    }

    //修改分类
    @ApiOperation(value = "修改分类")
    @PutMapping("/category")
    public ResultInfo update(@RequestBody Category c) {
        categoryService.update(c);
        // clean cache
        redisTemplate.delete("category_list");
        return ResultInfo.success();
    }

    //删除分类
    @ApiOperation(value = "删除分类")
    @DeleteMapping("/category")
    public ResultInfo delete(Long id) {
        ResultInfo resultInfo = categoryService.delete(id);
        // clean cache
        redisTemplate.delete("category_list");
        return ResultInfo.success();
    }
    /**
     * 新增菜品(回显菜品分类)
     * 套餐时查询的分类信息
     * @param type
     * @return
     */
    @ApiOperation(value = "根据类型查询分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "分类类型 1 菜品分类 2 套餐分类", required = true),
    })
    @GetMapping("/category/list")
    public ResultInfo findByType(Integer type) {
        List<Category> categoryList = categoryService.findByType(type);
        return ResultInfo.success(categoryList);
    }
}
